package com.xjscrm.console.service.customer.operatePlan.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.OptEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.tasktagauto.Condition;
import com.xjscrm.common.vo.tasktagauto.GroupSelect;
import com.xjscrm.common.vo.tasktagauto.ParaRule;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.operatePlan.TaskTagAutoDeviceQuery;
import com.xjscrm.console.param.wwCustomer.BatchCustomerTagDto;
import com.xjscrm.console.param.wwCustomer.CustomerQuery;
import com.xjscrm.console.param.wwCustomer.WwCustomerTagsQuery;
import com.xjscrm.console.service.customer.operatePlan.AutoTagTaskExcuteService;
import com.xjscrm.console.service.customer.wwCustomer.WwCustomerService;
import com.xjscrm.console.vo.WwCustomerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AutoTagTaskExcuteServiceImpl implements AutoTagTaskExcuteService {

@Autowired
private AutoTagPlanServiceMapper autoTagPlanServiceMapper;

@Autowired
private WwGroupMemberMapper wwGroupMemberMapper;

@Autowired
private WwCustomerMapper wwCustomerMapper;

@Autowired
private WwCustomerTagsMapper wwCustomerTagsMapper;

@Autowired
private WwCustomerService wwCustomerService;

@Autowired
private TaskTagAutoDeviceMapper taskTagAutoDeviceMapper;

@Autowired
private WwGroupMapper wwGroupMapper;

@Autowired
private WwDeviceMapper wwDeviceMapper;


    @Override
    @Async("taskExecutor")
    public void ExcuteAutoTagTask(TaskTagAuto taskTagAuto) {
        TaskTagAuto tagAuto = autoTagPlanServiceMapper.getById(taskTagAuto.getId(), taskTagAuto.getMerId());
        if (tagAuto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "任务不存在");
        }
        if (tagAuto.getStatus() == 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "任务已完成");
        }
        //事件触发，不做操作
        if (tagAuto.getParaType() == 2) {
            return;
        }

        if (StringUtils.isBlank(tagAuto.getParaRule())) {
            return;
        }
        ParaRule paraRule = JSONObject.parseObject(tagAuto.getParaRule(), ParaRule.class);

        if (paraRule != null) {
            //获取所有的客户
            CustomerQuery customerQuery = new CustomerQuery();
            Long idStart = 0L;
            customerQuery.setMerId(tagAuto.getMerId());
            customerQuery.setAsc(true);
            customerQuery.setCurrent(1);
            customerQuery.setSize(50);
            customerQuery.setOrderByField("id");
            customerQuery.setIdStart(idStart);
            String orderBy = OrderByUtil.getOrderBy(customerQuery.getOrderByField(), customerQuery.isAsc());
            PageHelper.startPage(customerQuery.getCurrent(),customerQuery.getSize(),orderBy);
            List<WwCustomerVo> customerVoList = wwCustomerMapper.getCustomer(customerQuery);
            while (customerVoList!=null&&!customerVoList.isEmpty()){
                for (WwCustomerVo wwCustomerVo:customerVoList) {
                    try {
                        if(wwCustomerVo.getId().longValue() > idStart.longValue()){
                            idStart = wwCustomerVo.getId();
                        }
                        boolean falg = ExcuteAutoTagTaskByCustomer(paraRule, wwCustomerVo);
                        if(falg){
                            addCustomerTags(wwCustomerVo, tagAuto);

                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                customerQuery.setIdStart(idStart);
                PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
                customerVoList = wwCustomerMapper.getCustomer(customerQuery);
            }
        }
       //完成后修改状态
        tagAuto.setStatus(1);
        autoTagPlanServiceMapper.updateTaskTagAuto(tagAuto);
    }

    private void addCustomerTags(WwCustomerVo wwCustomerVo, TaskTagAuto tagAuto) throws JsonProcessingException {
        //给客户打上标签
        if(tagAuto.getTagType()!=null&& tagAuto.getTagType()==1){
            if(tagAuto.getEnterpriseType()!=null&& tagAuto.getEnterpriseType()==0){
                BatchCustomerTagDto batchAddCustomerTagDto=new BatchCustomerTagDto();
                batchAddCustomerTagDto.setSelectType(0);
                batchAddCustomerTagDto.setCustomerIds(Arrays.asList(wwCustomerVo.getId()));
                ObjectMapper objectMapper = new ObjectMapper();
                batchAddCustomerTagDto.setTagIds(objectMapper.readValue(tagAuto.getEnterpriseTags(),List.class));
                batchAddCustomerTagDto.setDeviceUniqueId(wwCustomerVo.getDeviceUniqueId());
                batchAddCustomerTagDto.setType(1);
                batchAddCustomerTagDto.setMerId(wwCustomerVo.getMerId());
                wwCustomerService.batchAddCustomerTag(batchAddCustomerTagDto);
            }
            if(tagAuto.getEnterpriseType()!=null&& tagAuto.getEnterpriseType()==1){
             //获取改方案的机器人
                TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
                taskTagAutoDeviceQuery.setTaskId(tagAuto.getId());
                taskTagAutoDeviceQuery.setMerId(tagAuto.getMerId());
                List<TaskTagAutoDevice> taskTagAutoDeviceList = taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);
                List<Long> collect = taskTagAutoDeviceList.stream().map(TaskTagAutoDevice::getDeviceUniqueId).distinct().collect(Collectors.toList());
                if(collect.contains(wwCustomerVo.getDeviceUniqueId())){
                    BatchCustomerTagDto batchAddCustomerTagDto=new BatchCustomerTagDto();
                    batchAddCustomerTagDto.setSelectType(0);
                    batchAddCustomerTagDto.setCustomerIds(Arrays.asList(wwCustomerVo.getId()));
                    ObjectMapper objectMapper = new ObjectMapper();
                    batchAddCustomerTagDto.setTagIds(objectMapper.readValue(tagAuto.getEnterpriseTags(),List.class));
                    batchAddCustomerTagDto.setDeviceUniqueId(wwCustomerVo.getDeviceUniqueId());
                    batchAddCustomerTagDto.setType(1);
                    batchAddCustomerTagDto.setMerId(wwCustomerVo.getMerId());
                    wwCustomerService.batchAddCustomerTag(batchAddCustomerTagDto);
                }

            }
        }
        if(tagAuto.getTagType()!=null&& tagAuto.getTagType()==2){
            //获取个微标签列表
            TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
            taskTagAutoDeviceQuery.setTaskId(tagAuto.getId());
            taskTagAutoDeviceQuery.setMerId(tagAuto.getMerId());
            List<TaskTagAutoDevice> taskTagAutoDeviceList = taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);
            if(taskTagAutoDeviceList!=null&&!taskTagAutoDeviceList.isEmpty()){
                for (TaskTagAutoDevice taskTagAutoDevice:taskTagAutoDeviceList) {
                    try {
                        if(taskTagAutoDevice.getDeviceUniqueId()!=null&&taskTagAutoDevice.getDeviceUniqueId().equals(wwCustomerVo.getDeviceUniqueId())){
                            BatchCustomerTagDto batchAddCustomerTagDto=new BatchCustomerTagDto();
                            batchAddCustomerTagDto.setSelectType(0);
                            batchAddCustomerTagDto.setCustomerIds(Arrays.asList(wwCustomerVo.getId()));
                            ObjectMapper objectMapper = new ObjectMapper();
                            batchAddCustomerTagDto.setTagIds(objectMapper.readValue(taskTagAutoDevice.getPrivateTags(),List.class));
                            batchAddCustomerTagDto.setDeviceUniqueId(wwCustomerVo.getDeviceUniqueId());
                            batchAddCustomerTagDto.setType(1);
                            batchAddCustomerTagDto.setMerId(wwCustomerVo.getMerId());
                            wwCustomerService.batchAddCustomerTag(batchAddCustomerTagDto);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }



        }
    }

    private boolean ExcuteAutoTagTaskByCustomer(ParaRule paraRule, WwCustomerVo wwCustomerVo) {
        //满足任意条件的客户
        if (paraRule.getConditionType() != null && paraRule.getConditionType() == 0) {
            if (paraRule.getConditionList() != null && !paraRule.getConditionList().isEmpty()) {
                for (Condition condition : paraRule.getConditionList()) {
                    //获取所在客户群客户
                    if (condition.getItem() != null && condition.getItem() == 0) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.EQ.getValue())) {
                                if (condition.getGroupSelectList() != null && !condition.getGroupSelectList().isEmpty()) {
                                    for (GroupSelect groupSelect : condition.getGroupSelectList()) {
                                        if (groupSelect.getGroupWxidList() != null && !groupSelect.getGroupWxidList().isEmpty()) {
                                            for (String groupWxid : groupSelect.getGroupWxidList()) {
                                                WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(groupWxid, wwCustomerVo.getWxid(), wwCustomerVo.getMerId());
                                                WwGroup wwGroup = wwGroupMapper.getByGroupWxid(groupWxid, groupSelect.getDeviceId(), wwCustomerVo.getMerId());
                                                if (wwGroupMember != null&&wwGroup!=null) {
                                                    WwDevice wwDevice = wwDeviceMapper.getByDeviceId(groupSelect.getDeviceId(), wwCustomerVo.getMerId());
                                                    if(wwDevice!=null&&wwDevice.getId().equals(wwCustomerVo.getDeviceUniqueId())){
                                                        return true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //添加时间
                    if (condition.getItem() != null && condition.getItem() == 1) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.GT.getValue()) && condition.getCreateTime() != null) {
                                if (wwCustomerVo.getCreateTime() > condition.getCreateTime()) {
                                    return true;
                                }
                            }
                            if (condition.getOpt().equals(OptEnum.LT.getValue()) && condition.getCreateTime() != null) {
                                if (wwCustomerVo.getCreateTime() < condition.getCreateTime()) {
                                    return true;
                                }
                            }
                        }
                    }
                    //添加时间范围
                    if (condition.getItem() != null && condition.getItem() == 2) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.EQ.getValue()) && condition.getCreateTimeRange() != null) {
                                if (!StringUtils.isBlank(condition.getCreateTimeRange().getStartTime()) && !StringUtils.isBlank(condition.getCreateTimeRange().getEndTime())) {
                                    boolean betweenTimeRange = isBetweenTimeRange(Long.valueOf(wwCustomerVo.getCreateTime()), condition.getCreateTimeRange().getStartTime(), condition.getCreateTimeRange().getEndTime());
                                    if (betweenTimeRange) {
                                        return true;
                                    }

                                }
                            }
                        }
                    }
                    //企业标签
                    if (condition.getItem() != null && condition.getItem() == 3) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.CT.getValue())) {
                                if (condition.getEnterpriseTagList() != null && !condition.getEnterpriseTagList().isEmpty()) {
                                    WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
                                    wwCustomerTagsQuery.setTagIds(condition.getEnterpriseTagList());
                                    wwCustomerTagsQuery.setCustomerId(wwCustomerVo.getId());
                                    wwCustomerTagsQuery.setMerId(wwCustomerVo.getMerId());
                                    List<WwCustomerTags> wwCustomerTags = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
                                    if (wwCustomerTags != null && !wwCustomerTags.isEmpty()) {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
                return false;
            }
        }
        //满足所有条件
        if(paraRule.getConditionType() != null && paraRule.getConditionType() == 1){
            if (paraRule.getConditionList() != null && !paraRule.getConditionList().isEmpty()) {
                for (Condition condition : paraRule.getConditionList()) {
                    if (condition.getItem() != null && condition.getItem() == 0) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.EQ.getValue())) {
                                //获取所在客户群客户
                                if (condition.getGroupSelectList() != null && !condition.getGroupSelectList().isEmpty()) {
//                                    boolean WwGroupMemberFalg=false;
                                    for (GroupSelect groupSelect : condition.getGroupSelectList()) {
                                        if (groupSelect.getGroupWxidList() != null && !groupSelect.getGroupWxidList().isEmpty()) {
                                            for (String groupWxid : groupSelect.getGroupWxidList()) {
                                                WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(groupWxid, wwCustomerVo.getWxid(), wwCustomerVo.getMerId());
                                                WwGroup wwGroup = wwGroupMapper.getByGroupWxid(groupWxid, groupSelect.getDeviceId(), wwCustomerVo.getMerId());
                                                WwDevice wwDevice = wwDeviceMapper.getByDeviceId(groupSelect.getDeviceId(), wwCustomerVo.getMerId());
                                                if (wwGroupMember == null || wwGroup==null||wwDevice==null||!wwDevice.getId().equals(wwCustomerVo.getDeviceUniqueId())) {
                                                    return false;
                                                }
                                            }
                                        }
                                    }
//                                    if(!WwGroupMemberFalg){
//                                        return false;
//                                    }
                                }
                            }
                        }
                    }
                    //添加时间
                    if (condition.getItem() != null && condition.getItem() == 1) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.GT.getValue()) && condition.getCreateTime() != null) {
                                if (wwCustomerVo.getCreateTime() < condition.getCreateTime()) {
                                    return false;
                                }
                            }
                            if (condition.getOpt().equals(OptEnum.LT.getValue()) && condition.getCreateTime() != null) {
                                if (wwCustomerVo.getCreateTime() > condition.getCreateTime()) {
                                    return false;
                                }
                            }
                        }
                    }

                    //添加时间范围
                    if (condition.getItem() != null && condition.getItem() == 2) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.EQ.getValue()) && condition.getCreateTimeRange() != null) {
                                if (!StringUtils.isBlank(condition.getCreateTimeRange().getStartTime()) && !StringUtils.isBlank(condition.getCreateTimeRange().getEndTime())) {
                                    boolean betweenTimeRange = isBetweenTimeRange(Long.valueOf(wwCustomerVo.getCreateTime()), condition.getCreateTimeRange().getStartTime(), condition.getCreateTimeRange().getEndTime());
                                    if (!betweenTimeRange) {
                                        return false;
                                    }
                                }
                            }
                        }
                    }

                    //企业标签
                    if (condition.getItem() != null && condition.getItem() == 3) {
                        if (!StringUtils.isBlank(condition.getOpt())) {
                            if (condition.getOpt().equals(OptEnum.CT.getValue())) {
                                if (condition.getEnterpriseTagList() != null && !condition.getEnterpriseTagList().isEmpty()) {
                                    WwCustomerTagsQuery wwCustomerTagsQuery = new WwCustomerTagsQuery();
                                    wwCustomerTagsQuery.setTagIds(condition.getEnterpriseTagList());
                                    wwCustomerTagsQuery.setCustomerId(wwCustomerVo.getId());
                                    wwCustomerTagsQuery.setMerId(wwCustomerVo.getMerId());
                                    List<WwCustomerTags> wwCustomerTags = wwCustomerTagsMapper.getWwCustomerTags(wwCustomerTagsQuery);
                                    if (wwCustomerTags == null || wwCustomerTags.isEmpty()) {
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
        }
        return false;
    }



    public  boolean isBetweenTimeRange(Long createTime,String startTime,String endTime) {
//        Date date = new Date(createTime * 1000);
//        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
//        String time = sdf.format(date);
//        return time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0;

        Instant instant_groupCreateTime = Instant.ofEpochMilli(createTime * 1000L);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
        boolean withinTimeInterval_groupCreateTime = Tools.isWithinTimeInterval(localDateTime, LocalTime.parse(startTime), LocalTime.parse(endTime));
        return withinTimeInterval_groupCreateTime;
    }
}
